<script setup lang="ts">
import { formatDate, formatTime } from '@/utils/formatTime'
import { fenToYuan, yuanToFen } from '@/utils'
import * as RedPacketActivityApi from '@/api/promotion/redpacket/RedPacketActivityApi'

const ymd = formatDate(new Date(), 'YYYY-MM-DD')

const emit = defineEmits(['refresh'])

const activityDialog = reactive({
  visible: false,
  editIndex: -1,
  form: {
    id: undefined,
    type: undefined,
    startTime: '',
    endTime: '',
    thresholdPrice: 0,
    discountMode: 0,
    discountPrice: 0,
    enable: false
  }
})

const activityRules = {
  type: [{ required: true, message: '请选择红包类型', trigger: 'change' }],
  thresholdPrice: [{ required: true, message: '请输入门槛金额', trigger: 'blur' }],
  discountMode: [{ required: true, message: '请选择抵扣模式', trigger: 'change' }],
  discountPrice: [{ required: true, message: '请输入抵扣金额', trigger: 'blur' }]
}
const activityFormRef = ref()

const computedTimeRange = computed({
  get: () => {
    return [activityDialog.form.startTime, activityDialog.form.endTime]
  },
  set: (value) => {
    if (value.length !== 2) {
      return
    }
    activityDialog.form.startTime = ymd + ' ' + formatTime(value[0])
    activityDialog.form.endTime = ymd + ' ' + formatTime(value[1])
  }
})
const computedThresholdPrice = computed({
  get: () => {
    return Number(fenToYuan(activityDialog.form.thresholdPrice))
  },
  set: (value) => {
    activityDialog.form.thresholdPrice = yuanToFen(value)
  }
})
const computedDiscountPrice = computed({
  get: () => {
    return Number(fenToYuan(activityDialog.form.discountPrice))
  },
  set: (value) => {
    activityDialog.form.discountPrice = yuanToFen(value)
  }
})
const typeMap = {
  '1': { start: ymd + ' 06:00:00', end: ymd + ' 10:00:00' },
  '2': { start: ymd + ' 11:00:00', end: ymd + ' 14:00:00' },
  '3': { start: ymd + ' 16:00:00', end: ymd + ' 20:00:00' }
} as any

function onTypeChange(e?: number | string | boolean): any {
  const time = typeMap[e + '']
  //console.debug('type=', e, 'time=', time)
  if (time) {
    activityDialog.form.startTime = time.start
    activityDialog.form.endTime = time.end
  }
}

function onDiscountModeChange(e?: number | string | boolean): any {
  activityDialog.form.discountPrice = e === 1 ? 9999900 : 0
}

function openActivity(row: any) {
  Object.assign(activityDialog.form, row)
  activityDialog.visible = true
}

async function deleteActivity(row: any) {
  await RedPacketActivityApi.deleteById(row.id)
  emit('refresh')
}

async function saveActivity() {
  activityFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    if (activityDialog.form.id) {
      await RedPacketActivityApi.updateById(activityDialog.form)
    } else {
      await RedPacketActivityApi.create(activityDialog.form)
    }
    activityDialog.visible = false
    emit('refresh')
  })
}

defineExpose({ openActivity, deleteActivity })
</script>

<template>
  <el-drawer v-model="activityDialog.visible" title="红包抵扣规则" width="400px">
    <el-form
      ref="activityFormRef"
      :model="activityDialog.form"
      :rules="activityRules"
      label-width="90px"
    >
      <el-form-item label="红包类型" prop="type">
        <el-radio-group v-model="activityDialog.form.type" @change="onTypeChange">
          <el-radio :value="1">早餐</el-radio>
          <el-radio :value="2">午餐</el-radio>
          <el-radio :value="3">晚餐</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="timeRange">
        <template #label>
          <Tooltip title="抵扣时段" message="红包只能在指定的时间段内抵扣" />
        </template>
        <div>
          <el-time-picker
            v-model="computedTimeRange"
            is-range
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="HH:mm:ss"
          />
        </div>
      </el-form-item>
      <el-form-item prop="thresholdPrice">
        <template #label>
          <Tooltip title="门槛金额" message="消费需达到指定门槛才能抵扣" />
        </template>
        <el-input-number
          v-model="computedThresholdPrice"
          :min="0"
          :step="1"
          :precision="2"
          placeholder="请输入门槛金额"
          class="!w-240px"
        >
          <template #suffix>元</template>
        </el-input-number>
      </el-form-item>
      <el-form-item label="抵扣模式" prop="discountMode">
        <el-radio-group v-model="activityDialog.form.discountMode" @change="onDiscountModeChange">
          <el-radio :value="0">固定金额</el-radio>
          <el-radio :value="1">有多少抵扣多少</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="discountPrice">
        <template #label>
          <Tooltip title="抵扣金额" message="消费达到门槛后只能抵扣指定的金额" />
        </template>
        <el-input-number
          v-model="computedDiscountPrice"
          :min="0"
          :step="1"
          :precision="2"
          :disabled="activityDialog.form.discountMode === 1"
          placeholder="请输入抵扣金额"
          class="!w-240px"
        >
          <template #suffix>元</template>
        </el-input-number>
      </el-form-item>
      <el-form-item label="开关" prop="enable">
        <el-switch
          v-model="activityDialog.form.enable"
          :active-value="true"
          :inactive-value="false"
          active-text="开启"
          inactive-text="关闭"
          inline-prompt
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="activityDialog.visible = false">取消</el-button>
      <el-button type="primary" @click="saveActivity">保存</el-button>
    </template>
  </el-drawer>
</template>
